package com.shop.shopserver.config;

import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.EnableRabbit;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.retry.backoff.FixedBackOffPolicy;
import org.springframework.retry.policy.SimpleRetryPolicy;
import org.springframework.retry.support.RetryTemplate;


import java.util.HashMap;
import java.util.Map;

import static com.shop.shopcommon.constant.RabbitMQConstant.*;

@Slf4j
@Configuration
@EnableRabbit
public class RabbitMQConfiguration {

    // 第一个 RabbitTemplate 的配置 发送简单消息 发送不需要重试和生产者确认的消息
    @Bean(name = "rabbitSimpleTemplate")
    public RabbitTemplate rabbitSimpleTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        // 可以在这里进行第一个 RabbitTemplate 的特定配置
        // 例如设置消息转换器、确认回调等
        return rabbitTemplate;
    }

    // 第二个 RabbitTemplate 的配置 发送复杂消息 发送需要重试和生产者确认的消息
    @Bean(name = "rabbitComplexTemplate")
    public RabbitTemplate rabbitComplexTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        // 配置 RabbitTemplate 的 mandatory 属性 表示如果消息无法路由到任何队列，则会将消息返回给生产者（触发 ReturnCallback 回调）
        rabbitTemplate.setMandatory(true);

        // 设置 ConfirmCallback
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            if (ack) {
                log.info("消息发送成功，消息 ID: " + correlationData.getId());
            } else {
                log.info("消息发送失败，原因: " + cause + "，消息 ID: " + correlationData.getId());
            }
        });

        // 设置 ReturnsCallback
        rabbitTemplate.setReturnsCallback(returned -> {
            log.error("消息无法路由，返回内容: " + returned);
        });
//        rabbitTemplate.setReturnCallback((message, replyCode, replyText, exchange, routingKey) -> {
//            log.error("消息退回: replyCode={}, replyText={}, exchange={}, routingKey={}",
//                    replyCode, replyText, exchange, routingKey);
//        });

        // 配置重试模板
        RetryTemplate retryTemplate = new RetryTemplate ();
        // 配置重试策略，这里设置重试 3 次
        SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy ();
        retryPolicy.setMaxAttempts (3);
        retryTemplate.setRetryPolicy (retryPolicy);
        // 配置退避策略，这里设置每次重试间隔 1 秒
        FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy ();
        backOffPolicy.setBackOffPeriod (1000);
        retryTemplate.setBackOffPolicy (backOffPolicy);
        // 将重试模板设置到 RabbitTemplate 中
        rabbitTemplate.setRetryTemplate (retryTemplate);

        return rabbitTemplate;
    }


    // 创建一个短信交换器
    @Bean
    public CustomExchange smsExchange() {
        return new CustomExchange(SMS_EXCHANGE, "direct", true, true);
    }

    // 创建一个短信队列
    @Bean
    public Queue smsSendRequestQueue() {
        return QueueBuilder
                .durable(SMS_SEND_REQUEST_QUEUE)
                .autoDelete()
                .lazy() // 开启Lazy模式
                .build();
    }

    // 绑定短信队列到短信交换器
    @Bean
    public Binding smsBinding() {
        // 将队列绑定到交换器
        return BindingBuilder.bind(smsSendRequestQueue()).to(smsExchange()).with(SMS_SEND_REQUEST_ROUTING_KEY).noargs();
    }


    @Bean
    public CustomExchange delayedExchange() {
        // 创建一个延时交换器
        Map<String, Object> args = new HashMap<>();
        args.put("x-delayed-type", "direct"); // 指定延迟类型
        return new CustomExchange(DELAYED_EXCHANGE, "x-delayed-message", true, true, args);
    }

    @Bean
    public Queue delayedQueue() {
        return new Queue(DELAYED_QUEUE, true);
    }

    @Bean
    public Binding binding() {
        // 将队列绑定到交换器
        return BindingBuilder.bind(delayedQueue()).to(delayedExchange()).with(ROUTING_KEY).noargs();
    }
}